# app/schemas/base/error_codes.py
## 在services层 抛出 业务 错误码。。http错误码分开。
# controller层专注于 组合调用 services  。。services层 专注于业务判断 。。 api层专注于参数解析、依赖注入、返回数据
from dataclasses import dataclass
from typing import Dict, ClassVar

@dataclass(frozen=True)
class ErrorCode:
    code: int   ## http 错误码
    error_code:int  ## 业务错误码
    message: str
    remarks: str = ""

    # 缓存所有错误码，用于校验或文档生成
    _registry: ClassVar[Dict[int, 'ErrorCode']] = {}

    def __post_init__(self):
        # 自动注册
        ErrorCode._registry[self.code] = self

    @classmethod
    def get(cls, code: int) -> 'ErrorCode':
        return cls._registry.get(code, COMMON_ERROR)

    def format(self, **kwargs) -> 'FormattedErrorCode':
        """动态格式化错误信息"""
        return FormattedErrorCode(
            code = self.code,
            message = self.message.format(**kwargs),
            error_code = self.error_code,
            remarks = self.remarks.format(**kwargs) if self.remarks else ""
        )

@dataclass(frozen=True)
class FormattedErrorCode:
    code: int
    message: str
    error_code: int
    remarks: str = ""



# ========== 定义常量 ==========
COMMON_SUCCESS = ErrorCode(200,0, "操作成功")
COMMON_ERROR = ErrorCode(500, 1000,"系统异常,请稍后重试")

# ========== 通用错误类型 ==========
RESOURCE_NOT_FOUND = ErrorCode(404,1001, "{resource}不存在", "请检查{resource}ID是否正确")
RESOURCE_ACCESS_DENIED = ErrorCode(403,1002, "无权访问{resource}",  "您没有访问该{resource}的权限")
RESOURCE_CREATE_FAILED = ErrorCode(500,1003, "创建{resource}失败",  "系统内部错误，请稍后重试")
RESOURCE_UPDATE_FAILED = ErrorCode(500,1004, "更新{resource}失败",  "系统内部错误，请稍后重试")
RESOURCE_DELETE_FAILED = ErrorCode(500,1005, "删除{resource}失败",  "系统内部错误，请稍后重试")
RESOURCE_ALREADY_EXISTS = ErrorCode(409,1006, "{resource}已存在",   "请检查输入数据")
OPERATION_FAILED = ErrorCode(500,1007, "操作{resource}失败",  "请稍后重试")

# ========== 业务逻辑错误 ==========
VALIDATION_ERROR = ErrorCode(422, 2001, "数据验证失败",  "请检查提交的数据格式")
PERMISSION_DENIED = ErrorCode(403,2002, "权限不足",  "您没有执行此操作的权限")
BALANCE_NOT_ENOUGH = ErrorCode(200,2003, "余额不足",  "请充值后重试")  # 业务成功但逻辑失败

# ========== 系统错误 ==========
SYSTEM_ERROR = ErrorCode(500,9001, "系统异常",  "请稍后重试")
DATABASE_ERROR = ErrorCode(500,9002, "数据库异常",  "请稍后重试")

